{{define "content"}}
<div x-data="roleDetail()" x-init="$nextTick(() => init())">
    <!-- 页面标题 -->
    <div class="mb-6">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-2xl font-bold text-gray-900">角色详情</h1>
                <p class="text-gray-600">查看角色信息和权限分配</p>
            </div>
            <div class="flex space-x-3">
                <a href="/system/roles" class="bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700 flex items-center">
                    <i class="fas fa-arrow-left mr-2"></i>
                    返回角色列表
                </a>
                <a :href="'/system/roles/' + roleId + '/edit'" 
                   x-show="!loading && role.id" 
                   class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 flex items-center">
                    <i class="fas fa-edit mr-2"></i>
                    编辑角色
                </a>
            </div>
        </div>
    </div>

    <!-- 加载状态 -->
    <div x-show="loading" class="flex justify-center items-center py-12">
        <div class="text-center">
            <i class="fas fa-spinner fa-spin text-3xl text-blue-500 mb-4"></i>
            <p class="text-gray-600">加载中...</p>
        </div>
    </div>

    <!-- 角色信息 -->
    <div x-show="!loading" class="space-y-6">
        <!-- 基本信息卡片 -->
        <div class="bg-white rounded-lg shadow-sm p-6">
            <div class="flex items-start space-x-6">
                <!-- 角色头像 -->
                <div class="flex-shrink-0">
                    <div class="w-20 h-20 bg-purple-500 rounded-full flex items-center justify-center text-white text-2xl font-bold" 
                         x-text="role.display_name ? role.display_name.charAt(0).toUpperCase() : (role.name ? role.name.charAt(0).toUpperCase() : 'R')"></div>
                </div>
                
                <!-- 基本信息 -->
                <div class="flex-1">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div>
                            <h2 class="text-xl font-semibold text-gray-900 mb-2" x-text="role.display_name"></h2>
                            <div class="space-y-2">
                                <div class="flex items-center text-sm text-gray-600">
                                    <i class="fas fa-tag w-4 mr-2"></i>
                                    <span class="font-medium">角色名称：</span>
                                    <span x-text="role.name"></span>
                                </div>
                                <div class="flex items-center text-sm text-gray-600">
                                    <i class="fas fa-info-circle w-4 mr-2"></i>
                                    <span class="font-medium">状态：</span>
                                    <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full ml-1" 
                                          :class="role.status === 'active' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'" 
                                          x-text="role.status === 'active' ? '启用' : '停用'"></span>
                                </div>
                                <div class="flex items-center text-sm text-gray-600" x-show="role.description">
                                    <i class="fas fa-file-alt w-4 mr-2"></i>
                                    <span class="font-medium">描述：</span>
                                    <span x-text="role.description"></span>
                                </div>
                            </div>
                        </div>
                        
                        <div>
                            <div class="space-y-2">
                                <div class="flex items-center text-sm text-gray-600">
                                    <i class="fas fa-users w-4 mr-2"></i>
                                    <span class="font-medium">用户数量：</span>
                                    <span x-text="role.user_count || 0"></span>
                                </div>
                                <div class="flex items-center text-sm text-gray-600">
                                    <i class="fas fa-key w-4 mr-2"></i>
                                    <span class="font-medium">权限数量：</span>
                                    <span x-text="role.permission_count || 0"></span>
                                </div>
                                <div class="flex items-center text-sm text-gray-600">
                                    <i class="fas fa-calendar w-4 mr-2"></i>
                                    <span class="font-medium">创建时间：</span>
                                    <span x-text="formatDateTime(role.created_at)"></span>
                                </div>
                                <div class="flex items-center text-sm text-gray-600" x-show="role.updated_at">
                                    <i class="fas fa-edit w-4 mr-2"></i>
                                    <span class="font-medium">更新时间：</span>
                                    <span x-text="formatDateTime(role.updated_at)"></span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 权限列表卡片 -->
        <div class="bg-white rounded-lg shadow-sm">
            <div class="px-6 py-4 border-b border-gray-200">
                <div class="flex items-center justify-between">
                    <h3 class="text-lg font-medium text-gray-900">角色权限</h3>
                    <div class="text-sm text-gray-500">
                        共 <span x-text="permissions.length"></span> 个权限
                    </div>
                </div>
            </div>
            
            <div class="p-6">
                <div x-show="permissions.length === 0" class="text-center py-8 text-gray-500">
                    <i class="fas fa-key text-4xl mb-4"></i>
                    <p>该角色暂无分配权限</p>
                </div>
                
                <div x-show="permissions.length > 0" class="space-y-4">
                    <template x-for="group in permissionGroups" :key="group.name">
                        <div class="border border-gray-200 rounded-lg p-4">
                            <h4 class="text-md font-medium text-gray-900 mb-3 flex items-center">
                                <i class="fas fa-folder text-purple-500 mr-2"></i>
                                <span x-text="group.display_name"></span>
                                <span class="ml-2 text-sm text-gray-500">(<span x-text="group.permissions.length"></span>)</span>
                            </h4>
                            
                            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                                <template x-for="permission in group.permissions" :key="permission.id">
                                    <div class="flex items-center p-3 bg-gray-50 rounded-lg">
                                        <div class="flex-shrink-0">
                                            <i class="fas fa-check-circle text-green-500"></i>
                                        </div>
                                        <div class="ml-3">
                                            <div class="text-sm font-medium text-gray-900" x-text="permission.display_name"></div>
                                            <div class="text-xs text-gray-500" x-text="permission.name"></div>
                                        </div>
                                    </div>
                                </template>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </div>

        <!-- 关联用户卡片 -->
        <div class="bg-white rounded-lg shadow-sm">
            <div class="px-6 py-4 border-b border-gray-200">
                <div class="flex items-center justify-between">
                    <h3 class="text-lg font-medium text-gray-900">关联用户</h3>
                    <div class="text-sm text-gray-500">
                        共 <span x-text="users.length"></span> 个用户
                    </div>
                </div>
            </div>
            
            <div class="p-6">
                <div x-show="users.length === 0" class="text-center py-8 text-gray-500">
                    <i class="fas fa-users text-4xl mb-4"></i>
                    <p>该角色暂无关联用户</p>
                </div>
                
                <div x-show="users.length > 0" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                    <template x-for="user in users" :key="user.id">
                        <div class="flex items-center p-4 border border-gray-200 rounded-lg hover:bg-gray-50">
                            <div class="flex-shrink-0">
                                <div class="w-10 h-10 bg-blue-500 rounded-full flex items-center justify-center text-white font-medium" 
                                     x-text="getUserInitials(user.real_name || user.username)"></div>
                            </div>
                            <div class="ml-3 flex-1">
                                <div class="text-sm font-medium text-gray-900">
                                    <a :href="'/system/users/' + user.id" class="hover:text-blue-600" x-text="user.real_name || user.username"></a>
                                </div>
                                <div class="text-sm text-gray-500" x-text="user.username"></div>
                                <div class="text-xs text-gray-400">
                                    <span class="inline-flex px-2 py-1 text-xs font-semibold rounded-full" 
                                          :class="user.status === 'active' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'" 
                                          x-text="user.status === 'active' ? '启用' : '停用'"></span>
                                </div>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function roleDetail() {
    return {
        // 数据
        role: {},
        permissions: [],
        permissionGroups: [],
        users: [],
        
        // 状态
        loading: true,
        roleId: null,
        initialized: false,
        
        // 初始化
        async init() {
            // 防止重复初始化
            if (this.initialized) {
                return;
            }
            this.initialized = true;
            
            this.roleId = this.getRoleIdFromUrl();
            if (!this.roleId) {
                this.showToast('角色ID无效', 'error');
                window.location.href = '/system/roles';
                return;
            }
            
            await this.loadRoleData();
            await this.loadRolePermissions();
            await this.loadRoleUsers();
            this.loading = false;
        },
        
        // 从URL获取角色ID
        getRoleIdFromUrl() {
            const pathParts = window.location.pathname.split('/');
            const rolesIndex = pathParts.indexOf('roles');
            if (rolesIndex >= 0 && rolesIndex < pathParts.length - 1) {
                return pathParts[rolesIndex + 1];
            }
            return null;
        },
        
        // 加载角色数据
        async loadRoleData() {
            try {
                const response = await fetch(`/api/v1/system/roles/${this.roleId}`);
                const result = await response.json();
                
                if (result.code === 200) {
                    this.role = result.data;
                } else if (result.message === '用户未登录') {
                    window.location.href = '/auth/login';
                } else {
                    this.showToast(result.message || '加载角色信息失败', 'error');
                    window.location.href = '/system/roles';
                }
            } catch (error) {
                console.error('加载角色数据失败:', error);
                this.showToast('加载角色信息失败', 'error');
                window.location.href = '/system/roles';
            }
        },
        
        // 加载角色权限
        async loadRolePermissions() {
            try {
                const response = await fetch(`/api/v1/system/roles/${this.roleId}/permissions`);
                const result = await response.json();
                
                if (result.code === 200) {
                    this.permissions = result.data || [];
                    this.groupPermissions();
                } else if (result.message === '用户未登录') {
                    window.location.href = '/auth/login';
                }
            } catch (error) {
                console.error('加载角色权限失败:', error);
            }
        },
        
        // 加载角色用户
        async loadRoleUsers() {
            try {
                const response = await fetch(`/api/v1/system/roles/${this.roleId}/users`);
                const result = await response.json();
                
                if (result.code === 200) {
                    this.users = result.data || [];
                } else if (result.message === '用户未登录') {
                    window.location.href = '/auth/login';
                }
            } catch (error) {
                console.error('加载角色用户失败:', error);
            }
        },
        
        // 权限分组
        groupPermissions() {
            const groups = {};
            this.permissions.forEach(permission => {
                const groupName = permission.name.split('.')[0];
                if (!groups[groupName]) {
                    groups[groupName] = {
                        name: groupName,
                        display_name: this.getGroupDisplayName(groupName),
                        permissions: []
                    };
                }
                groups[groupName].permissions.push(permission);
            });
            this.permissionGroups = Object.values(groups);
        },
        
        // 获取权限组显示名称
        getGroupDisplayName(groupName) {
            const groupNames = {
                'user': '用户管理',
                'role': '角色管理',
                'permission': '权限管理',
                'customer': '客户管理',
                'partner': '合作伙伴',
                'push': '推送管理',
                'system': '系统管理'
            };
            return groupNames[groupName] || groupName;
        },
        
        // 获取用户姓名首字母
        getUserInitials(name) {
            if (!name) return 'U';
            const names = name.trim().split(' ');
            if (names.length >= 2) {
                return (names[0].charAt(0) + names[1].charAt(0)).toUpperCase();
            }
            return name.charAt(0).toUpperCase();
        },
        
        // 格式化日期时间
        formatDateTime(dateTime) {
            if (!dateTime) return '-';
            return new Date(dateTime).toLocaleString('zh-CN');
        },
        
        // 显示提示信息
        showToast(message, type = 'info') {
            // 这里可以集成一个 toast 组件
            console.log(`${type}: ${message}`);
            alert(message);
        }
    };
}
</script>
{{end}}